const logger = require("../utils/logger")
const mysqlUtil = require("../utils/mysqlUtil")
const commonModule = require('./common')
const moment = require('moment')
const util = require("../utils/util")

module.exports = {
    // 传阅文件
    chuanyueWenjian: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('chuanyue wenjian', params)

        params.auditors = params.auditors || []
        let auditorsObj = {}
        for (let i = 0; i != params.auditors.length; i++) {
            auditorsObj['auditor' + i] = { uid: params.auditors[i].uid, stepName: params.auditors[i].stepName, sta: 0 }
        }

        try {
            let res = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '玩家不存在'})
            let name = res[0].name

            // 编号自动生成 查询今年已经有多少申请了
            res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_chuanyue_apply WHERE createTime > ?', [moment().startOf('year').valueOf()])
            let year = new Date().getFullYear()
            let cnt = res[0].cnt
            let bianhao = ''
            if (cnt < 10) {
                bianhao = year + '00' + cnt
            } else if (cnt < 100) {
                bianhao = year  + '0' + cnt
            } else {
                bianhao = year + '' + cnt
            }

            let sql = 'INSERT INTO tb_user_chuanyue_apply SET ?'
            res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 0,
                auditSta: 1,
                bianhao,
                danwei: params.danwei,
                wenhao: params.wenhao || '',
                biaoti: params.biaoti,
                shouwenDate: params.shouwenDate,
                zhaiyao: params.zhaiyao,
                readers: JSON.stringify(params.readers || []),
                attaches: JSON.stringify(params.attaches || []),
                fileTag: parseInt(params.fileTag || 0),
                pics: JSON.stringify(params.pics || []),
                auditors: JSON.stringify(auditorsObj),
                createTime: Date.now()
            }])
            
            let applyId = res.insertId

            let content = params.biaoti
            // 为审核人员添加任务
            await mysqlUtil.execute('INSERT INTO tb_user_task SET ?', [{
                uid: params.auditors[0].uid,
                typ: 17,
                relevenceId: applyId,
                pos: 0,
                title: content,
                content,
                sta: 0,
                createTime: Date.now()
            }])
            io.in(params.auditors[0].uid + '-app').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-app').emit('TASK-NEW')
            io.in(params.auditors[0].uid + '-web').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-web').emit('TASK-NEW')

            // 添加发起人到传阅文件关联表中
            await mysqlUtil.execute('INSERT INTO tb_user_chuanyue_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                uid,
                relevenceId: applyId,
                updateTime: Date.now()
            }, Date.now()])

            // 添加第一个审核人到传阅文件关联表中
            await mysqlUtil.execute('INSERT INTO tb_user_chuanyue_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                uid: params.auditors[0].uid,
                relevenceId: applyId,
                updateTime: Date.now()
            }, Date.now()])

            let attaches = params.attaches || []
            let file1Name = ''
            if (attaches.length > 0) {
                file1Name = attaches[0].name || ''
            }
            let smsContent = '文件传阅审批'
            if (file1Name) {
                if (file1Name.length > 20) {
                    file1Name = file1Name.slice(0, 19) + '...'
                }
                smsContent = smsContent + '【' + file1Name + '】'
            }

            util.sendReminderSmsToUser(params.auditors[0].uid, smsContent, '待审批')
            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    revertChuanyueWenjian: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_chuanyue_apply SET chexiao = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '撤销失败'})
            // 将审核人员的任务状态改下 并通知前端
            res = await mysqlUtil.execute('SELECT id, uid FROM tb_user_task WHERE typ = 17 AND relevenceId = ?', [params.id])
            for (let i = 0; i != res.length; i++) {
                await mysqlUtil.execute('UPDATE tb_user_task SET sta = 3 WHERE id = ? LIMIT 1', [res[i].id])
                // 通知前端
                io.in(res[i].uid + '-app').emit('TASK-REVERT', res[i].id)
                io.in(res[i].uid + '-web').emit('TASK-REVERT', res[i].id)
            }
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    chuanyueWenjianRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10
        // 关键字
        let keyword = params.keyword || ''
        // 文件类型
        let fileTag = parseInt(params.fileTag || 0)

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE id < ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, lessThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND id < ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, lessThan, fileTag, pageCount]
                    }
                }
            } else if (greaterThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE id > ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, greaterThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND id > ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, greaterThan, fileTag, pageCount]
                    }
                }
            } else {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, fileTag, pageCount]
                    }
                }
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    chuanyueWenjianRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);
        let keyword = params.keyword || ''
        let fileTag = parseInt(params.fileTag || 0)

        try {
            let sqlCnt = ''
            let sqlCntParams = []
            let sql = ''
            let sqlParams = []
            if (keyword) {
                sqlCnt = `
                    SELECT COUNT(1) cnt FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    `
                sqlCntParams = [uid, uid]

                sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?, ?
                    `
                sqlParams = [uid, uid, (pageIndex - 1) * pageCount, pageCount]

                if (fileTag) {
                    sqlCnt = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ?
                    `
                    sqlCntParams = [uid, uid, fileTag]

                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ? ORDER BY id DESC LIMIT ?, ?
                    `
                    sqlParams = [uid, uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            } else {
                sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?)'
                sqlCntParams = [uid]
                sql = 'SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?, ?'
                sqlParams = [uid, (pageIndex - 1) * pageCount, pageCount]
                if (fileTag) {
                    sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND fileTag = ?'
                    sqlCntParams = [uid, fileTag]
                    sql = 'SELECT * FROM tb_user_chuanyue_apply WHERE id IN (SELECT relevenceId FROM tb_user_chuanyue_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?, ?'
                    sqlParams = [uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            }

            let res = await mysqlUtil.execute(sqlCnt, sqlCntParams)
            let count = res[0].cnt
            res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    chuanyueWenjianDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let shoucang = 0
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user_gongwen_shoucang WHERE uid = ? AND relevenceId = ? AND typ = 17', [uid, params.id])
            if (res.length != 0) shoucang = 1
            res = await mysqlUtil.execute('SELECT * FROM tb_user_chuanyue_apply WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            res[0].shoucang = shoucang

            let applyInfo = res[0]
            applyInfo.auditors = applyInfo.auditors || []
            for (let key in applyInfo.auditors) {
                let sql = `
                    SELECT
                        con_position.name
                    FROM
                        tb_user
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    WHERE tb_user.uid = ?
                    LIMIT 1
                `
                let r = await mysqlUtil.execute(sql, [applyInfo.auditors[key].uid])
                if (r.length > 0) {
                    applyInfo.auditors[key].positionName = r[0].name
                }
            }
            callback({code: 0, message: '', data: applyInfo})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 公文流转
    gongwenLiuzhuan: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('gongwenLiuzhuan', params)

        if (!Array.isArray(params.attaches)) {
            return callback({code: -1, message: '参数错误'})
        }

        let auditorsObj = {}
        for (let i = 0; i != params.auditors.length; i++) {
            auditorsObj['auditor' + i] = { uid: params.auditors[i].uid, stepName: params.auditors[i].stepName, sta: 0 }
        }

        try {
            let res = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '玩家不存在'})
            let name = res[0].name

            // 编号自动生成 查询今年已经有多少申请了
            res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_liuzhuan_apply WHERE createTime > ?', [moment().startOf('year').valueOf()])
            let year = new Date().getFullYear()
            let cnt = res[0].cnt
            let bianhao = ''
            if (cnt < 10) {
                bianhao = year + '00' + cnt
            } else if (cnt < 100) {
                bianhao = year  + '0' + cnt
            } else {
                bianhao = year + '' + cnt
            }

            let sql = 'INSERT INTO tb_user_liuzhuan_apply SET ?'
            res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 0,
                auditSta: 1,
                bianhao,
                danwei: params.danwei,
                wenhao: params.wenhao || '',
                biaoti: params.biaoti,
                chengwenDate: params.chengwenDate,
                zhaiyao: params.zhaiyao,
                readers: JSON.stringify(params.readers || []),
                attaches: JSON.stringify(params.attaches || []),
                fileTag: parseInt(params.fileTag || 0),
                auditors: JSON.stringify(auditorsObj),
                createTime: Date.now()
            }])

            let applyId = res.insertId

            let content = params.biaoti
            // 为审核人员添加任务
            await mysqlUtil.execute('INSERT INTO tb_user_task SET ?', [{
                uid: params.auditors[0].uid,
                typ: 18,
                relevenceId: applyId,
                pos: 0,
                title: content,
                content,
                sta: 0,
                createTime: Date.now()
            }])
            io.in(params.auditors[0].uid + '-app').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-app').emit('TASK-NEW')
            io.in(params.auditors[0].uid + '-web').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-web').emit('TASK-NEW')

            // 添加发起人到公文流转关联表中
            await mysqlUtil.execute('INSERT INTO tb_user_liuzhuan_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                uid,
                relevenceId: applyId,
                updateTime: Date.now()
            }, Date.now()])

            // 添加第一个审核人到公文流转关联表中
            await mysqlUtil.execute('INSERT INTO tb_user_liuzhuan_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                uid: params.auditors[0].uid,
                relevenceId: applyId,
                updateTime: Date.now()
            }, Date.now()])

            let attaches = params.attaches || []
            let file1Name = ''
            if (attaches.length > 0) {
                file1Name = attaches[0].name || ''
            }
            let smsContent = '公文流转审批'
            if (file1Name) {
                if (file1Name.length > 20) {
                    file1Name = file1Name.slice(0, 19) + '...'
                }
                smsContent = smsContent + '【' + file1Name + '】'
            }

            util.sendReminderSmsToUser(params.auditors[0].uid, smsContent, '待审批')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    revertGongwenLiuzhuan: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_liuzhuan_apply SET chexiao = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '撤销失败'})
            // 将审核人员的任务状态改下 并通知前端
            res = await mysqlUtil.execute('SELECT id, uid FROM tb_user_task WHERE typ = 18 AND relevenceId = ?', [params.id])
            for (let i = 0; i != res.length; i++) {
                await mysqlUtil.execute('UPDATE tb_user_task SET sta = 3 WHERE id = ? LIMIT 1', [res[i].id])
                // 通知前端
                io.in(res[i].uid + '-app').emit('TASK-REVERT', res[i].id)
                io.in(res[i].uid + '-web').emit('TASK-REVERT', res[i].id)
            }
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 完成公文流转
    finishGongwenLiuzhuan: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user_liuzhuan_apply WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '申请不存在'})
            let applyInfo = res[0]
            res = await mysqlUtil.execute('UPDATE tb_user_liuzhuan_apply SET sta = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '完成失败'})
            // 将审核人员的任务状态改下 并通知前端
            res = await mysqlUtil.execute('SELECT id, uid FROM tb_user_task WHERE typ = 18 AND relevenceId = ?', [params.id])
            for (let i = 0; i != res.length; i++) {
                await mysqlUtil.execute('UPDATE tb_user_task SET sta = 1 WHERE id = ? LIMIT 1', [res[i].id])
                // 通知前端
                io.in(res[i].uid + '-app').emit('TASK-CHANGE', res[i].id)
                io.in(res[i].uid + '-web').emit('TASK-CHANGE', res[i].id)
            }

            let uids = []
            for (let k in applyInfo.auditors) {
                if (uids.indexOf(applyInfo.auditors[k].uid) != -1) continue
                uids.push(applyInfo.auditors[k].uid)
            }

            for (let k in applyInfo.chengbanren) {
                if (uids.indexOf(applyInfo.chengbanren[k].uid) != -1) continue
                uids.push(applyInfo.chengbanren[k].uid)
            }

            for (let i = 0; i != applyInfo.readers.length; i++) {
                if (uids.indexOf(applyInfo.readers[i].uid) != -1) continue
                uids.push(applyInfo.readers[i].uid)
            }

            for (let i = 0; i != uids.length; i++) {
                let uid = uids[i]
                await mysqlUtil.execute('INSERT INTO tb_user_gongwen_history SET ?', [{
                    uid,
                    title: applyInfo.biaoti,
                    content: applyInfo.zhaiyao || applyInfo.biaoti,
                    relevenceId: applyInfo.id,
                    typ: 18,
                    gongwenTime: applyInfo.createTime,
                    createTime: Date.now()
                }])
            }

            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongwenLiuzhuanRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10
        let keyword = params.keyword || ''
        let fileTag = params.fileTag || ''

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE id < ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, lessThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND id < ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, lessThan, fileTag, pageCount]
                    }
                }
            } else if (greaterThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE id > ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, greaterThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND id > ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, greaterThan, fileTag, pageCount]
                    }
                }
            } else {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                        t1
                        WHERE fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, fileTag, pageCount]
                    }
                }
            }

            let res = await mysqlUtil.execute(sql, sqlParams)
            // 查询申请人名称
            for (let i = 0; i != res.length; i++) {
                let r = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [res[i].uid])
                res[i].uName = r[0].name
                if (res[i].attaches && typeof res[i].attaches == 'string') {
                    res[i].attaches = JSON.parse(res[i].attaches)
                }
                if (res[i].auditors && typeof res[i].auditors == 'string') {
                    res[i].auditors = JSON.parse(res[i].auditors)
                }
                if (res[i].chengbanren && typeof res[i].chengbanren == 'string') {
                    res[i].chengbanren = JSON.parse(res[i].chengbanren)
                }
                if (res[i].readers && typeof res[i].readers == 'string') {
                    res[i].readers = JSON.parse(res[i].readers)
                }
            }
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongwenLiuzhuanRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);
        let keyword = params.keyword || ''
        let fileTag = parseInt(params.fileTag || 0)

        try {
            let sqlCnt = ''
            let sqlCntParams = []
            let sql = ''
            let sqlParams = []
            if (keyword) {
                sqlCnt = `
                    SELECT COUNT(1) cnt FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    `
                sqlCntParams = [uid, uid]

                sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?, ?
                    `
                sqlParams = [uid, uid, (pageIndex - 1) * pageCount, pageCount]

                if (fileTag) {
                    sqlCnt = `
                    SELECT COUNT(1) cnt FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ?
                    `
                    sqlCntParams = [uid, uid, fileTag]

                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ? ORDER BY id DESC LIMIT ?, ?
                    `
                    sqlParams = [uid, uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            } else {
                sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?)'
                sqlCntParams = [uid]
                sql = 'SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?, ?'
                sqlParams = [uid, (pageIndex - 1) * pageCount, pageCount]
                if (fileTag) {
                    sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND fileTag = ?'
                    sqlCntParams = [uid, fileTag]
                    sql = 'SELECT * FROM tb_user_liuzhuan_apply WHERE id IN (SELECT relevenceId FROM tb_user_liuzhuan_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?, ?'
                    sqlParams = [uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            }

            let res = await mysqlUtil.execute(sqlCnt, sqlCntParams)
            let count = res[0].cnt
            res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongwenLiuzhuanDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let shoucang = 0
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user_gongwen_shoucang WHERE uid = ? AND relevenceId = ? AND typ = 18', [uid, params.id])
            if (res.length != 0) shoucang = 1
            res = await mysqlUtil.execute('SELECT * FROM tb_user_liuzhuan_apply WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            res[0].shoucang = shoucang
            let applyInfo = res[0]
            applyInfo.auditors = applyInfo.auditors || []
            for (let key in applyInfo.auditors) {
                let sql = `
                    SELECT
                        con_position.name
                    FROM
                        tb_user
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    WHERE tb_user.uid = ?
                    LIMIT 1
                `
                let r = await mysqlUtil.execute(sql, [applyInfo.auditors[key].uid])
                if (r.length > 0) {
                    applyInfo.auditors[key].positionName = r[0].name
                }
            }
            callback({code: 0, message: '', data: applyInfo})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongwenliuzhuanYueban: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})
        let id = parseInt(params.id || 0)

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user_liuzhuan_apply WHERE id = ? LIMIT 1', [id])
            if (res.length == 0) return callback({code: -1, message: '申请不存在'})
            let applyInfo = res[0]
            applyInfo.readers = applyInfo.readers || []
            let found = false
            for (let i = 0; i != applyInfo.readers.length; i++) {
                if (applyInfo.readers[i].uid == uid) {
                    applyInfo.readers[i].sta = 1
                    found = true
                    break
                }
            }

            if (!found) {
                return callback({code: -1, message: '你不是该公文的经办人'})
            }

            await mysqlUtil.execute('UPDATE tb_user_liuzhuan_apply SET readers = ? WHERE id = ? LIMIT 1', [JSON.stringify(applyInfo.readers), id])

            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取公文信息
    getGongwenInfo: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    tb_gongwen.*,
                    tb_user_gongwen_shoucang.id shoucangId
                FROM
                    tb_gongwen
                    LEFT JOIN tb_user_gongwen_shoucang ON tb_gongwen.id = tb_user_gongwen_shoucang.gongwenId AND tb_user_gongwen_shoucang.uid = ?
                WHERE tb_gongwen.id = ?
                LIMIT 1
            `
            let res = await mysqlUtil.execute(sql, [uid, params.id])
            if (res.length == 0) return callback({code: -1, message: '公文不存在'})
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 收藏公文
    shoucangGongwen: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id || !params.typ || !params.title) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('INSERT INTO tb_user_gongwen_shoucang SET ?', [{
                uid,
                title: params.title || '',
                content: params.content || '',
                relevenceId: params.id,
                typ: params.typ,
                createTime: Date.now()
            }])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 取消收藏
    cancelShoucang: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id || !params.typ) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('DELETE FROM tb_user_gongwen_shoucang WHERE uid = ? AND typ = ? AND relevenceId = ?', [uid, params.typ, params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取历史公文列表，加了个类型
    getGongwenHistoryListType: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})
        callback = callback || commonModule.emptyFunc

        let typ = params.typ
        if (typ != 17 && typ != 18 && typ != 23)  return callback({code: -1, message: '参数错误'})
        let pageStart = params.pageStart || 0
        let pageCount = params.pageCount || 10
        let keyword = params.keyword || ''

        let year = params.year || 0
        let month = params.month || 0
        let day = params.day || 0

        let startTime = 0
        let endTime = 0
        if (year != 0) {
            startTime = moment(year + '-01-01 00:00:00').startOf('year').valueOf()
            endTime = moment(year + '-01-01 00:00:00').endOf('year').valueOf()
            if (month != 0) {
                startTime = moment(year + '-' + month + '-01 00:00:00').startOf('month').valueOf()
                endTime = moment(year + '-' + month + '-01 00:00:00').endOf('month').valueOf()
                if (day != 0) {
                    startTime = moment(year + '-' + month + '-' + day + ' 00:00:00').startOf('day').valueOf()
                    endTime = moment(year + '-' + month + '-' + day + ' 00:00:00').endOf('day').valueOf()
                }
            }
        }

        let sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND typ = ? '
        let sqlParams = [uid, typ]
        if (startTime!= 0 && endTime!= 0) {
            sql += 'AND createTime BETWEEN ? AND ? '
            sqlParams.push(startTime, endTime)
        }

        if (keyword != '') {
            sql += `AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') `
        }

        sql += 'ORDER BY gongwenTime DESC LIMIT ?, ?'
        sqlParams.push(pageStart, pageCount)

        try {
            let res = await mysqlUtil.execute(sql, sqlParams)
            for (let i = 0; i != res.length; i++) {
                res[i].createTime = res[i].gongwenTime
            }
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message:'system error'})
        }
    },

    // 获取公文历史列表
    getGongwenHistoryList: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = parseInt(params.lessThan || 0)
        // 大于的id
        let greaterThan = parseInt(params.greaterThan || 0)
        // 每页的数量
        let pageCount = parseInt(params.pageCount || 10)

        let keyword = params.keyword || ''
        let fileTag = parseInt(params.fileTag || 0)

        let year = parseInt(params.year || 0)
        let month = parseInt(params.month || 0)
        let day = parseInt(params.day || 0)

        let startTime = 0
        let endTime = 0
        if (year != 0) {
            startTime = moment(year + '-01-01 00:00:00').startOf('year').valueOf()
            endTime = moment(year + '-01-01 00:00:00').endOf('year').valueOf()
            if (month != 0) {
                startTime = moment(year + '-' + month + '-01 00:00:00').startOf('month').valueOf()
                endTime = moment(year + '-' + month + '-01 00:00:00').endOf('month').valueOf()
                if (day != 0) {
                    startTime = moment(year + '-' + month + '-' + day + ' 00:00:00').startOf('day').valueOf()
                    endTime = moment(year + '-' + month + '-' + day + ' 00:00:00').endOf('day').valueOf()
                }
            }
        }

        try {
            if (keyword) {
                let sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC`
                let sqlParams = [uid]
                if (startTime) {
                    sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ? AND ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC`
                    sqlParams = [uid, startTime, endTime]
                }
                if (fileTag) {
                    sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') AND fileTag = ? ORDER BY gongwenTime DESC`
                    sqlParams = [uid, fileTag]
                    if (startTime) {
                        sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ? AND ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC`
                        sqlParams = [uid, fileTag, startTime, endTime]
                    }
                }
                let res = await mysqlUtil.execute(sql, sqlParams)
                return callback({code: 0, message: 'success', data: res})
            }

            let sql = ''
            let sqlParams = []
            if (lessThan) {
                if (fileTag) {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND id < ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, fileTag, lessThan, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ? AND ? AND id < ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, fileTag, startTime, endTime, lessThan, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND id < ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, lessThan, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ? AND ? AND id < ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, startTime, endTime, lessThan, pageCount]
                    }
                }
            } else if (greaterThan) {
                if (fileTag) {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND id > ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, fileTag, greaterThan, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ? AND ? AND id > ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, fileTag, startTime, endTime, greaterThan, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND id > ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, greaterThan, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ? AND ? AND id > ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, startTime, endTime, greaterThan, pageCount]
                    }
                }
            } else {
                if (fileTag) {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, fileTag, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ?  AND createTime BETWEEN ? AND ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, startTime, endTime, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? ORDER BY gongwenTime DESC LIMIT ?'
                    sqlParams = [uid, pageCount]
                    if (startTime) {
                        sql = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ?  AND createTime BETWEEN ? AND ? ORDER BY gongwenTime DESC LIMIT ?'
                        sqlParams = [uid, startTime, endTime, pageCount]
                    }
                }
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            for (let i = 0; i != res.length; i++) {
                res[i].createTime = res[i].gongwenTime
            }
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getGongwenHistoryListWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        let keyword = params.keyword || ''
        let fileTag = parseInt(params.fileTag || 0)

        let year = parseInt(params.year || 0)
        let month = parseInt(params.month || 0)
        let day = parseInt(params.day || 0)

        let startTime = 0
        let endTime = 0
        if (year != 0) {
            startTime = moment(year + '-01-01 00:00:00').startOf('year').valueOf()
            endTime = moment(year + '-01-01 00:00:00').endOf('year').valueOf()
            if (month != 0) {
                startTime = moment(year + '-' + month + '-01 00:00:00').startOf('month').valueOf()
                endTime = moment(year + '-' + month + '-01 00:00:00').endOf('month').valueOf()
                if (day != 0) {
                    startTime = moment(year + '-' + month + '-' + day + ' 00:00:00').startOf('day').valueOf()
                    endTime = moment(year + '-' + month + '-' + day + ' 00:00:00').endOf('day').valueOf()
                }
            }
        }

        try {
            if (keyword) {
                let sql = `SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%')`
                if (startTime) {
                    sql = `SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ${startTime} AND ${endTime} AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%')`
                }
                let params = [uid]
                if (fileTag) {
                    sql = `SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%')`
                    if (startTime) {
                        sql = `SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ${startTime} AND ${endTime} AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%')`
                    }
                    params = [uid, fileTag]
                }

                let res = await mysqlUtil.execute(sql, params)
                let count = res[0].cnt
                sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC LIMIT ?, ?`
                params = [uid, (pageIndex - 1) * pageCount, pageCount]
                if (startTime) {
                    sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ? AND ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC LIMIT ?, ?`
                    params = [uid, startTime, endTime, (pageIndex - 1) * pageCount, pageCount]
                }
                if (fileTag) {
                    sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC LIMIT ?, ?`
                    params = [uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                    if (startTime) {
                        sql = `SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ? AND ? AND (content LIKE '%${keyword}%' OR title LIKE '%${keyword}%') ORDER BY gongwenTime DESC LIMIT ?, ?`
                        params = [uid, fileTag, startTime, endTime, (pageIndex - 1) * pageCount, pageCount]
                    }
                }
                logger.debug(uid, sql, params)
                res = await mysqlUtil.execute(sql, params)
                return callback({code: 0, message: 'success', data: {list: res, count}})
            }

            let sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ?'
            let paramsCnt = [uid]
            if (fileTag) {
                sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ?'
                paramsCnt = [uid, fileTag]
            }
            let res = await mysqlUtil.execute(sqlCnt, paramsCnt)
            let count = res[0].cnt
            let sqlRes = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? ORDER BY gongwenTime DESC LIMIT ?, ?'
            let paramsRes = [uid, (pageIndex - 1) * pageCount, pageCount]
            if (startTime) {
                sqlRes = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND createTime BETWEEN ? AND ? ORDER BY gongwenTime DESC LIMIT ?, ?'
                paramsRes = [uid, startTime, endTime, (pageIndex - 1) * pageCount, pageCount]
            }
            if (fileTag) {
                sqlRes = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? ORDER BY gongwenTime DESC LIMIT ?, ?'
                paramsRes = [uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                if (startTime) {
                    sqlRes = 'SELECT * FROM tb_user_gongwen_history WHERE uid = ? AND fileTag = ? AND createTime BETWEEN ? AND ? ORDER BY gongwenTime DESC LIMIT ?, ?'
                    paramsRes = [uid, fileTag, startTime, endTime, (pageIndex - 1) * pageCount, pageCount]
                }
            }
            res = await mysqlUtil.execute(sqlRes, paramsRes)
            for (let i = 0; i != res.length; i++) {
                res[i].createTime = res[i].gongwenTime
            }
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取公文收藏列表
    getGongwenShoucangList: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                sql = 'SELECT * FROM tb_user_gongwen_shoucang WHERE uid = ? AND id < ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, lessThan, pageCount]
            } else if (greaterThan) {
                sql = 'SELECT * FROM tb_user_gongwen_shoucang WHERE uid = ? AND id > ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, greaterThan, pageCount]
            } else {
                sql = 'SELECT * FROM tb_user_gongwen_shoucang WHERE uid = ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, pageCount]
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongwenShoucangListWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_gongwen_shoucang WHERE uid = ?', [uid])
            let count = res[0].cnt
            let sql = 'SELECT * FROM tb_user_gongwen_shoucang WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 内部发文
    neibuFawen: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('neibuFawen', params)

        try {
            let res = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '玩家不存在'})
            let name = res[0].name

            let sql = 'INSERT INTO tb_user_neibu_fawen SET ?'
            res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 1,
                biaoti: params.biaoti,
                neirong: params.neirong,
                readers: JSON.stringify(params.readers || []),
                attaches: JSON.stringify(params.attaches || []),
                fileTag: parseInt(params.fileTag || 0),
                pics: JSON.stringify(params.pics || []),
                createTime: Date.now()
            }])
            
            let applyId = res.insertId

            // 添加发起人到内部发文关联表中
            await mysqlUtil.execute('INSERT INTO tb_user_neibu_fawen_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                uid,
                relevenceId: applyId,
                updateTime: Date.now()
            }, Date.now()])

            // 给分发范围添加通知
            // 通知读者
            for (let i = 0; i != params.readers.length; i++) {

                // 添加读者到内部发文关联表中
                await mysqlUtil.execute('INSERT INTO tb_user_neibu_fawen_relevence SET ? ON DUPLICATE KEY UPDATE updateTime = ? ', [{
                    uid: params.readers[i].uid,
                    relevenceId: applyId,
                    updateTime: Date.now()
                }, Date.now()])

                await mysqlUtil.execute('INSERT INTO tb_user_notification SET ?', [{
                    uid: params.readers[i].uid, // 通知读者
                    typ: 23,
                    title: params.biaoti,
                    content: params.biaoti,
                    sta: 0,
                    resTyp: 3,
                    relevenceId: applyId,
                    createTime: Date.now()
                }])

                // 保存到历史公文
                await mysqlUtil.execute('INSERT INTO tb_user_gongwen_history SET ?', [{
                    uid: params.readers[i].uid,
                    title: params.biaoti,
                    content: params.neirong || params.biaoti,
                    relevenceId: applyId,
                    fileTag: parseInt(params.fileTag || 0),
                    typ: 23,
                    gongwenTime: Date.now(),
                    createTime: Date.now()
                }])
            }

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    neibuFawenRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10
        let keyword = params.keyword || ''
        let fileTag = parseInt(params.fileTag || 0)

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                    t1
                    WHERE id < ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                        t1
                        WHERE id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, lessThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND id < ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, lessThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND id < ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, lessThan, fileTag, pageCount]
                    }
                }
            } else if (greaterThan) {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                    t1
                    WHERE id > ? ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                        t1
                        WHERE id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, greaterThan, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND id > ? ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, greaterThan, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND id > ? AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, greaterThan, fileTag, pageCount]
                    }
                }
            } else {
                if (keyword) {
                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?
                    `
                    sqlParams = [uid, uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM (
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                            UNION
                            SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND neirong LIKE '%${keyword}%')
                        t1
                        WHERE fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, uid, fileTag, pageCount]
                    }
                } else {
                    sql = 'SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?'
                    sqlParams = [uid, pageCount]
                    if (fileTag) {
                        sql = `
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?
                        `
                        sqlParams = [uid, fileTag, pageCount]
                    }
                }
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    neibuFawenRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        let fileTag = parseInt(params.fileTag || 0)
        let keyword = params.keyword || ''

        try {
            let sqlCnt = ''
            let sqlCntParams = []
            let sql = ''
            let sqlParams = []
            if (keyword) {
                sqlCnt = `
                    SELECT COUNT(1) cnt FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    `
                sqlCntParams = [uid, uid]

                sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    ORDER BY id DESC LIMIT ?, ?
                    `
                sqlParams = [uid, uid, (pageIndex - 1) * pageCount, pageCount]

                if (fileTag) {
                    sqlCnt = `
                    SELECT COUNT(1) cnt FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ?
                    `
                    sqlCntParams = [uid, uid, fileTag]

                    sql = `
                    SELECT * FROM (
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND biaoti LIKE '%${keyword}%'
                        UNION
                        SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND zhaiyao LIKE '%${keyword}%')
                    t1
                    WHERE fileTag = ? ORDER BY id DESC LIMIT ?, ?
                    `
                    sqlParams = [uid, uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            } else {
                sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?)'
                sqlCntParams = [uid]
                sql = 'SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) ORDER BY id DESC LIMIT ?, ?'
                sqlParams = [uid, (pageIndex - 1) * pageCount, pageCount]
                if (fileTag) {
                    sqlCnt = 'SELECT COUNT(1) cnt FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND fileTag = ?'
                    sqlCntParams = [uid, fileTag]
                    sql = 'SELECT * FROM tb_user_neibu_fawen WHERE id IN (SELECT relevenceId FROM tb_user_neibu_fawen_relevence WHERE uid = ?) AND fileTag = ? ORDER BY id DESC LIMIT ?, ?'
                    sqlParams = [uid, fileTag, (pageIndex - 1) * pageCount, pageCount]
                }
            }

            let res = await mysqlUtil.execute(sqlCnt, sqlCntParams)
            let count = res[0].cnt
            res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    neibuFawenDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let shoucang = 0
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user_gongwen_shoucang WHERE uid = ? AND relevenceId = ? AND typ = 23', [uid, params.id])
            if (res.length != 0) shoucang = 1
            res = await mysqlUtil.execute('SELECT * FROM tb_user_neibu_fawen WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            res[0].shoucang = shoucang
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    revertNeibuFawen: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        logger.debug('revert neibufawen', params)

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_neibu_fawen SET chexiao = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '撤销失败'})
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 文件标签列表
    fileTagList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})
        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_file_tag')
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 添加文件标签
    fileTagAdd: async (io, socket, params, callback) => {
        callback = callback || commonModule.emptyFunc
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        if (!params.name) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('INSERT INTO tb_file_tag SET ?', [{name: params.name}])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改文件标签
    fileTagModify: async (io, socket, params, callback) => {
        callback = callback || commonModule.emptyFunc
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        if (!params.id || !params.name) return callback({code: -1, message: '参数缺失'})
        
        try {
            await mysqlUtil.execute('UPDATE tb_file_tag SET name = ? WHERE id = ? LIMIT 1', [params.name, parseInt(params.id)])
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },
}